package cc.lishixi.book.service;

import cc.lishixi.book.dao.mapper.BookRowMapper;
import cc.lishixi.book.entity.Book;
import cc.lishixi.book.service.api.AbstractService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by LiShixi on 2016/7/23 0023.
 * http://www.lishixi.cc
 */
@Component
public class BookService extends AbstractService<Book> {

    public List<Book> list() {
        return jdbcTemplate.query("select * from book", new BookRowMapper());
    }

    @Override
    public boolean delete(Integer id) {
        return jdbcTemplate.update("delete from book where id = ?", id) > 0;
    }

    @Override
    public boolean edit(Book book) {
        String sql = "UPDATE `book`.`book` SET `isbn`=?, `name`=?, `series`=?, `authors`=?, `publisher`=?, `size`=?, `pages`=?, `price`=?, `introduction`=?, `picture`=?, `clnum`=? " +
                "WHERE  `id`=?;";
        return jdbcTemplate.update(sql,
                book.getName(),
                book.getSeries(),
                book.getAuthors(),
                book.getPublisher(),
                book.getSize(),
                book.getPages(),
                book.getPrice(),
                book.getIntroduction(),
                book.getPicture(),
                book.getClnum(),
                book.getId()
        ) > 0;
    }

    @Override
    public boolean add(Book b) {
        String sql = "INSERT INTO `book`.`book` (`isbn`, `name`, `series`, `authors`, `publisher`, `size`, `pages`, `price`, `introduction`, `picture`, `clnum`) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        return jdbcTemplate.update(sql,
                b.getIsbn(),
                b.getName(),
                b.getSeries(),
                b.getAuthors(),
                b.getPublisher(),
                b.getSize(),
                b.getPages(),
                b.getPrice(),
                b.getIntroduction(),
                b.getPicture(),
                b.getClnum()
        ) > 0;
    }

    public List<Book> findByName(String name){
        String sql="select * from book where `name` like ?";
        return jdbcTemplate.query(sql,new BookRowMapper(),"%"+name+"%");
    }

    public List<Book> findByIsbn(String isbn){
        String sql="select * from book where isbn like ?";
        List<Book> books = jdbcTemplate.query(sql,new BookRowMapper(),"%"+ isbn+"%");
        return books;
    }

    public List<Book> findBypublisher(String publisher){
        String sql="select * from book where publisher like ?";
        List<Book> books = jdbcTemplate.query(sql,new BookRowMapper(),"%"+ publisher+"%");
        return books;
    }

    public List<Book> findByAuthor(String author){
        String sql="select * from book where authors like ?";
        List<Book> books = jdbcTemplate.query(sql,new BookRowMapper(), "%"+author+"%");
        return books;
    }
}
